<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
      <el-form-item label="作业/试卷名称" prop="className">
        <el-input
          v-model="queryParams.testpaperName"
          placeholder="请输入作业/试卷名称"
          clearable
          size="small"
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="适用专业">
        <el-select v-model="queryParams.major" clearable filterable>
          <el-option
            v-for="item in majorList"
            :label="item.subjectName+''"
            :value="item.id+''"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="适用科目">
        <el-select v-model="queryParams.subjectId" clearable filterable size="small">
          <el-option
            v-for="dict in subjectList"
            :key="dict.id"
            :label="dict.subjName"
            :value="dict.id+''"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="classify">
        <el-select v-model="queryParams.classify" clearable filterable>
          <el-option value="1" label="日常作业"></el-option>
          <el-option value="2" label="考试试卷"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增作业/试卷</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addFiles">新建文件夹</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="openRemove"
          :disabled="buttonShow"
        >移动到</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="bclassList"
      @selection-change="handleSelectionChange"
      row-key="id"
      lazy
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      :load="load"
    >
      <el-table-column
        label="序号"
        align="left"
        width="80"
        type="selection"
        :selectable="handleDisable"
      ></el-table-column>
      <el-table-column label="试卷名" align="center">
        <template slot-scope="scope">
          <div style="display:flex" class="hezi" v-if="scope.row.showInp == 0">
            <div>
              <i class="iconfont icon-wenjianjia-copy"></i>
            </div>
            <div style="display:flex">
              <el-input v-model="scope.row.testpaperName"></el-input>
              <div class="smallIcon">
                <i class="el-icon-check" @click="addFile(scope.row)"></i>
              </div>
              <div class="smallIcon">
                <i class="el-icon-close" @click="deleteFile(scope.row)"></i>
              </div>
            </div>
          </div>
          <div
            v-else
            style="display:flex"
            :class="[scope.row.hasChildren == false ? 'classIcon' : '' ]"
          >
            <div style="margin-right:5px" v-if="scope.row.type == 1">
              <i class="iconfont icon-fenshijuan-copy"></i>
            </div>
            <div style="margin-right:5px" v-if="scope.row.type == 0">
              <i class="iconfont icon-wenjianjia-copy"></i>
            </div>
            {{ scope.row.testpaperName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="left" prop="type" width="120">
        <template
          slot-scope="scope"
        >{{ scope.row.type == "0" ? "文件夹" : (scope.row.type == "1" ? "试卷" : "")}}</template>
      </el-table-column>
      <el-table-column
        label="专业"
        align="left"
        prop="major"
        :show-overflow-tooltip="true"
        width="120"
      >
        <template slot-scope="scope">{{ getMajorLable(scope.row.major) }}</template>
      </el-table-column>
      <el-table-column
        label="科目"
        align="left"
        prop="subjectId"
        :show-overflow-tooltip="true"
        width="120"
      >
        <template slot-scope="scope">{{ getSubjectLable(scope.row.subjectId) }}</template>
      </el-table-column>
      <el-table-column
        label="分类"
        align="left"
        prop="classify"
        :show-overflow-tooltip="true"
        width="120"
      >
        <template slot-scope="scope">
          <label v-if="scope.row.classify==1">日常作业</label>
          <label v-if="scope.row.classify==2">考试试卷</label>
        </template>
      </el-table-column>
      <el-table-column
        label="年級"
        align="left"
        prop="grade"
        width="160"
        :show-overflow-tooltip="true"
        >
        <template slot-scope="scope">{{ selectDictLabel(classGradeList, scope.row.grade) }}</template>
      </el-table-column>
      <el-table-column label="总分" align="left" prop="totalPoints" width="120"></el-table-column>
      <el-table-column label="操作" align="left" width="160">
        <template slot-scope="scope">
          <el-tooltip
            class="item"
            effect="dark"
            content="移动到"
            placement="top"
            v-if="scope.row.type == 1"
          >
            <el-button
              size="mini"
              circle
              type="primary"
              icon="el-icon-thumb"
              @click="openRemoveButton(scope.row)"
            />
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="编辑"
            placement="top"
            v-if="scope.row.type == 1"
          >
            <el-button
              size="mini"
              circle
              type="success"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            />
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="删除"
            placement="top"
            v-if="scope.row.type == 1"
          >
            <el-button
              size="mini"
              circle
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            />
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="发布"
            placement="top"
            v-if="scope.row.type == 1"
          >
            <el-button
              size="mini"
              circle
              icon="el-icon-s-promotion"
              @click="handlePublish(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="重命名"
            placement="top"
            v-if="scope.row.type == 0"
          >
            <el-button
              size="mini"
              circle
              type="success"
              icon="el-icon-edit"
              @click="changeFileName(scope.row)"
            />
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="删除"
            placement="top"
            v-if="scope.row.type == 0"
          >
            <el-button
              size="mini"
              circle
              type="danger"
              icon="el-icon-delete"
              @click="removeFile(scope.row)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- <el-table :data="newClassList">
      <el-table-column align="center" type="selection"></el-table-column>
      <el-table-column label="试卷名" align="center" width="460">
        <template slot-scope="scope">
          <div style="display:flex" class="hezi">
            <div>
              <i class="el-icon-folder"></i>
            </div>
            <div style="display:flex">
              <el-input v-model="fileName"></el-input>
              <div>
                <i class="el-icon-check"></i>
              </div>
              <div>
                <i class="el-icon-close"></i>
              </div>
            </div>
          </div>
          <div>

          </div>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" width="120"></el-table-column>
      <el-table-column label="修改日期" align="center" width="560"></el-table-column>
      <el-table-column label="操作" align="center" width="280"></el-table-column>
    </el-table>-->

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--试卷发布信息填写-->
    <el-dialog title="试题发布" :visible.sync="publishAperVisible" width="400px">
      <el-form :model="form" ref="form" :rules="rules" label-width="110px">
        <el-form-item label="发布班级" prop="classId">
          <el-select v-model="selectedValues" multiple>
            <el-option
              v-for="item in classOptions"
              :key="item.id"
              :label="item.className"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布类型" prop="pubilishType">
          <el-select v-model="form.pubilishType">
            <el-option value="1" v-if="form.type==1" label="日常作业"></el-option>
            <el-option value="2"  v-if="form.type==2" label="考试试卷"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPublish" :loading="submitLoading">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 移动到 -->
    <el-dialog title="移动到" :visible.sync="removeShow" width="400px" center>
      <div class="block">
        <el-tree
          :data="fileList"
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
          @node-click="checkFile"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <div style="display:flex;">
              <div style="margin-right:5px">
                <i class="iconfont icon-wenjianjia-copy"></i>
              </div>
              <span>{{ node.label }}</span>
            </div>
          </span>
        </el-tree>
      </div>
      <el-divider></el-divider>
      <div class="button">
        <el-button @click="removeShow = false">取消</el-button>
        <el-button type="primary" @click="submitRemove">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

  <script>
import { findSchoolClassPageList } from "@/api/classManage/classInfo";
import { findBaseSpaceLocationPageList } from "@/api/baseData/siteManagement";
import { getClassTeacherList } from "@/api/system/user";
import { findBaseSubjectPageList } from "@/api/baseData/profession";
import { listTermtime } from "@/api/system/termtime.js";
import {
  tExamTestpaperPageList,
  deleteTestPaper,
  publishTestPaper
} from "@/api/studentInfo/taskAndPaper";
import {
  subjectList,
  editFolder,
  deleteFolder,
  findMysafeAllFolder,
  changeToFolder
} from "@/api/educational/subject.js";
import { Scope } from "quill";
export default {
  name: "BClass",
  data() {
    return {
      selectedValues:[],
      buttonShow: true,
      // 文件夹pid
      piod: "",
      // 选中需要移动试卷的集合
      removePapeList: {},
      // 文件夹集合
      fileList: [],
      // 判断是哪个按钮
      buttonType: "",
      // 文件夹名字
      fileName: "",

      submitLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      rowList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      stuCount: 0,
      // 字典表格数据
      bclassList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 班主任
      userOptions: [],
      // 状态数据字典
      statusOptions: [],
      // 班级所属部门
      classDeptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        className: undefined,
        status: undefined,
        classDept: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        classId: [
          { required: true, message: "考试名称不能为空", trigger: "blur" }
        ],
        pubilishType: [
          { required: true, message: "考试开始时间不能为空", trigger: "blur" }
        ]
      },
      subjectList: [],
      majorList: [], //专业
      termTimeList: [],
      courseTypeOptions: [],
      classOptions: [],
      classGradeList: [],
      publishAperVisible: false,
      removeShow: false,
      count: "",
      rwoParmars:[],
    };
  },
  created() {
    this.getMajortList();
    this.getList();
    this.getClassTeacherList();
    this.getSubjectList();
    this.getTermTimeList();
    this.getClassList();

    this.getDicts("class_grade").then(response => {
      //年级
      this.classGradeList = response.data;
    });
  },
  methods: {
    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
          <span>
            <el-button
              size="mini"
              type="text"
              on-click={() => this.append(data)}
            >
              Append
            </el-button>
            <el-button
              size="mini"
              type="text"
              on-click={() => this.remove(node, data)}
            >
              Delete
            </el-button>
          </span>
        </span>
      );
    },
    // 文件夹小箭头下拉的函数
    load(tree, treeNode, resolve) {
      console.log(tree);
      tExamTestpaperPageList({ pid: tree.id, pageNum: 1, pageSize: 100 }).then(
        res => {
          resolve(res.data.list);
        }
      );
      console.log(1111);
    },
    // 树形图选择文件夹
    checkFile(data) {
      this.pid = data.id;
    },
    // 确认移动
    submitRemove() {
      if (this.rwoParmars.length !=0 ) {
        let obj = {};
        obj.pid = this.pid;
        obj.testPaperList = this.rwoParmars;
        console.log(obj);
        changeToFolder(obj).then(res => {
          console.log(res);
          this.removeShow = false;
          this.getList();
        });
      } else {
        let obj = {};
        obj.pid = this.pid;
        obj.testPaperList = this.removePapeList;
        console.log(obj);
        changeToFolder(obj).then(res => {
          console.log(res);
          this.removeShow = false;
          this.getList();
        });
      }
    },
    // 文件夹禁用
    handleDisable(row, index) {
      if (row.type == 0) {
        return false;
      } else {
        return true;
      }
    },
    //
    openRemoveButton(row) {
      this.openRemove();
      this.rwoParmars.push(row)
      console.log(this.rwoParmars);
    },
    // 移动到按钮函数
    openRemove() {
      this.fileList = [];
      this.removeShow = true;
      findMysafeAllFolder({}).then(res => {
        console.log(res);
        res.data.forEach(item => {
          this.fileList.push({ label: item.testpaperName, id: item.id });
        });
        let arr = [{}];
        arr[0].label = "全部文件";
        arr[0].id = 0;
        arr[0].children = this.fileList;
        this.fileList = arr;
        console.log(arr);
      });
    },
    // 按钮的删除
    removeFile(row) {
      let arr = [];
      arr.push(row.id);
      this.$confirm("是否确认删除此文件夹?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return deleteFolder(arr);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    // 重命名文件夹
    changeFileName(row) {
      this.buttonType = 2;
      this.$set(row, "showInp", "0");
      // console.log(row)
      this.fileName = row.testpaperName;
    },
    // 编辑时候的删除
    deleteFile(row) {
      if (this.buttonType == 2) {
        this.$set(row, "showInp", "1");
      }
      if (this.buttonType == 1) {
        this.bclassList = this.bclassList.filter(item => {
          return item.index !== row.index;
        });
      }
      console.log(this.bclassList);
    },
    // 新增文件夹
    addFile(row) {
      // console.log(row)
      if (row.testpaperName) {
        editFolder(row).then(res => {
          console.log(res);
          this.msgSuccess("操作成功");
          this.$set(row, "showInp", "1");
        });
      } else {
        this.$message({
          message: "请输入文件夹名字",
          type: "warning"
        });
      }
    },
    // 新建文件夹
    addFiles() {
      this.count++;
      this.buttonType = 1;
      this.fileName = "";
      this.bclassList.unshift({
        showInp: "0",
        index: this.count
      });
    },
    handlePublish(row) {
      this.form = {
        testPaperId: row.id,
        classId: null,
        pubilishType: null,
        type:row.classify
      };
      this.publishAperVisible = true;
    },
    getClassRoom() {
      findBaseSpaceLocationPageList({
        pageNum: 1,
        pageSize: 1000,
        locationType: 4
      }).then(response => {
        this.classRoomOptions = response.data.list;
      });
    },
    getClassList() {
      //查询班级
      findSchoolClassPageList({
        pageSize: 500,
        pageNum: 1,
        status: 1,
        isGraduation: 0
      }).then(resp => {
        this.classOptions = resp.data.list;
      });
    },
    getTermTimeList() {
      //查询学期
      this.loading = true;
      listTermtime({ pageSize: 100, pageNum: 1, status: 1 }).then(response => {
        this.termTimeList = response.data.list;
      });
    },
    getMajortList() {
      //查询科目
      findBaseSubjectPageList({ pageSize: 100, pageNum: 1, status: 1 }).then(
        response => {
          this.majorList = response.data.list;
        }
      );
    },
    getSubjectList() {
      //查询专柜
      subjectList({ pageSize: 100, pageNum: 1, status: 1 }).then(response => {
        this.subjectList = response.data.list;
      });
    },
    getMajorLable(val) {
      for (let i = 0; i < this.majorList.length; i++) {
        if (this.majorList[i].id == val) {
          return this.majorList[i].subjectName;
        }
      }
    },
    getSubjectLable(val) {
      for (let i = 0; i < this.subjectList.length; i++) {
        if (this.subjectList[i].id == val) {
          return this.subjectList[i].subjName;
        }
      }
    },
    /** 查询班级列表 */
    getList() {
      this.loading = true;
      tExamTestpaperPageList(this.queryParams).then(response => {
        this.bclassList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
        console.log(this.bclassList);
        console.log("-----------");
      });
    },
    getClassTeacherList() {
      getClassTeacherList().then(response => {
        this.userOptions = response.data;
      });
    },
    // 字典设备状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 字典设备状态字典翻译
    classDeptFormat(row, column) {
      return this.selectDictLabel(this.classDeptOptions, row.classDept);
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        className: undefined,
        classTeacherId: undefined,
        status: "1",
        classDept: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageSize: 10,
        pageNum: 1,
        testpaperName: null,
        major: null,
        subjectId: null,
        classify: null
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push("/educational/exam/editPaper");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.buttonShow = !selection.length;
      console.log(selection);
      this.rowList = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.removePapeList = selection;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({
        path: "/educational/exam/editPaper",
        query: { id: row.id }
      });
    },
    submitPublish() {
      this.submitLoading = true;
      const publishAllTestPapers = async () => {
        this.submitLoading = true;
        for (let i = 0; i < this.selectedValues.length; i++) {
          this.form.classId = this.selectedValues[i];
          try {
            await publishTestPaper(this.form);
          } catch (error) {
            this.submitLoading = false;
          }
        }
        this.msgSuccess("发布成功");
        this.submitLoading = false;
      };

      publishAllTestPapers();
          this.submitLoading = false;
          this.publishAperVisible = false;
    },
    handleClose() {
      this.publishAperVisible = false;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return deleteTestPaper(row.id);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },

    // 获取当前选中班主任的名称
    selectUser(val) {
      alert(val.label);
      this.form.username = val.label;
    }
  }
};
</script>
<style scoped lang="scss">
.tubiao {
  text-align: center;
  line-height: 39px;
  font-size: 30px;
  margin-right: 10px;
}
.hezi {
  font-size: 20px;
  text-align: center;
  line-height: 36px;
  div {
    margin-right: 10px;
  }
}
.smallIcon {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 72px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  margin: auto 0;
}
.button {
  text-align: center;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 18px;
}
/deep/.cell {
  display: flex;
}
.classIcon {
  margin-left: 23px;
}
/deep/.el-input--medium .el-input__inner {
  height: 30px;
}
</style>>
